\section{Introduction to Python}

\centeredlargetext{white}{black}{
Introduction to Python
}


\subsection{Using IPython}

\begin{frame}
\frametitle{Playing with Python Interpreters}
\begin{itemize}
  \item IPython is a Python interpreter with additional interactive capabilities and
        more MATLAB-like features, discussed later.
  \item We will start with IPython to learn the basics and then move to
        Spyder when working with Python script files.
  \pause
  \item Note: both Python and IPython can be run in a terminal with no need for a GUI.
  \begin{itemize}
    \vspace{-0.5em}
    \item To test this, click \includegraphics[height=1.5em]{Icons/gnome-terminal}\, in the launcher to open a terminal.
    \item Type \textbf{python} to start Python and \textbf{ipython} to start IPython.
    \item If your prompt is \pyprompt\, you have a standard Python interpreter.
    \setcounter{ipycommand}{0}
    \item If your prompt is \ipyprompt\, you have an IPython interpreter.
    \item Type \textbf{quit()} or \textbf{Ctrl-D} to exit, or close the terminal.
  \end{itemize}
\end{itemize}
\vspace{-0.5em}
\begin{columns}[t]
\column{0.4\textwidth}
\centering
\includegraphics[width=\textwidth]{ScreenShot/terminal-python}\\[-0.25em]
\footnotesize
Python Interpreter
\column{0.4\textwidth}
\centering
\includegraphics[width=\textwidth]{ScreenShot/terminal-ipython}\\[-0.25em]
\footnotesize
IPython Interpreter
\end{columns}
\end{frame}


\begin{frame}[fragile]
\frametitle{Launch the IPython Qt Console}
\overlayicon{Icons/ipython}
\begin{itemize}
  \item Open the IPython Qt Console by clicking \includegraphics[height=1.5em]{Icons/ipython}\, in the launcher.
\end{itemize}
\begin{center}
  \includegraphics[width=0.70\paperwidth]{ScreenShot/ipython-qt-console}
\end{center}
\end{frame}


\subsection{Python Interpreter Examples}


\begin{frame}[fragile]
\frametitle{Basic Math}
\reference{
More Examples: \url{http://docs.python.org/tutorial/introduction.html}
}
\begin{itemize}
\item Try typing commands directly into the IPython interpreter.
\end{itemize}
\setcounter{ipycommand}{0}
\begin{lstlisting}
(*@\ipyprompt@*) 2 + 2        # This is a comment
(*@\ipyreturn@*) 4

(*@\ipyprompt@*) 2.0 + 2.0    # Floating point addition
(*@\ipyreturn@*) 4.0

(*@\ipyprompt@*) 5.0 / 2      # Floating point division
(*@\ipyreturn@*) 2.5

(*@\ipyprompt@*) 5 / 2        # Integer division (in Python3 this returns 2.5)
(*@\ipyreturn@*) 2

(*@\ipyprompt@*) 5.0 // 2.0   # Double slash forces integer division
(*@\ipyreturn@*) 2.0

(*@\ipyprompt@*) 5 % 2        # 5 modulo 2, in MATLAB this is mod(5,2)
(*@\ipyreturn@*) 1

(*@\ipyprompt@*) 3 ** 2       # Exponentiation, in MATLAB this is 3^2
(*@\ipyreturn@*) 9

(*@\ipyprompt@*) _ + 2        # Underscore is the last returned value, in MATLAB this is 'ans'
(*@\ipyreturn@*) 11
\end{lstlisting}
\end{frame}


\subsection{Basic Types}


\begin{frame}
\frametitle{Basic Built-in Types}
\reference{
More info: \url{http://docs.python.org/library/stdtypes.html}
}
\begin{itemize}
\item Basic Numerical Types
  \begin{itemize}
  \item \lstpy{int} - Integer type with unlimited precision (in Python 3).
  \item \lstpy{float} - Floating point type (usually double precision).
  \item \lstpy{complex} - Complex number with real and imaginary float components.
  \pause
  \item Note: in Python 2 \lstpy{int} has limited precision and
        separate type \lstpy{long} has unlimited precision.
  \end{itemize}
\pause
\item Special Types
  \begin{itemize}
  \item \lstpy{bool} - Boolean with values \lstpy{False} or \lstpy{True}.
  \item \lstpy{None} - A null object, more about this later.
  \end{itemize}
\pause
\item Container Types
  \begin{itemize}
  \item \lstpy{str} - A string of characters.
  \item \lstpy{tuple} - A fixed sequence of objects.
  \item \lstpy{list} - A mutable sequence of objects.
  \item \lstpy{dict} - A dictionary mapping one set of objects to another.
  \item Plus various lesser used containers.
  \end{itemize}
\pause
\item Additional numerical types and containers are provided by NumPy.
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Type Conversions}
\reference{
More info: \url{http://docs.python.org/library/stdtypes.html}
}
\begin{itemize}
\item Types are easily converted using the syntax \lstpy{type(object)}
\item Type conversion even works to and from strings
\item Some type conversions (e.g. complex to float) are not well defined and throw an exception.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) float(7)
(*@\ipyreturn@*) 7.0

(*@\ipyprompt@*) int(3.14159)
(*@\ipyreturn@*) 3

(*@\ipyprompt@*) str(28)
(*@\ipyreturn@*) '28'

(*@\ipyprompt@*) float('5.5')
(*@\ipyreturn@*) 5.5

(*@\ipyprompt@*) complex(4.5)
(*@\ipyreturn@*) (4.5+0j)

(*@\ipyprompt@*) bool(0)
(*@\ipyreturn@*) False

(*@\ipyprompt@*) float(True)
(*@\ipyreturn@*) 1.0
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
\frametitle{Assignment}
\reference{
More Examples: \url{http://docs.python.org/tutorial/introduction.html}
}
\begin{itemize}
\item Variables are created during assignment
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) my_var
(*@\texttt{\color{red}{------------------------------------------------------------}}@*)
(*@\texttt{Traceback {\color{cyan}(most recent call last)}:}@*)
  (*@\texttt{{\color{cyan}File {\color{green}"<ipython console>"}, line 1, in} \color{magenta}{<module>}}@*)
(*@\texttt{{\color{red}NameError:} name 'my\_var' is not defined}@*)

(*@\ipyprompt@*) my_var = 10

(*@\ipyprompt@*) my_var
(*@\ipyreturn@*) 10
\end{lstlisting}
\begin{itemize}
\item Other assignment examples
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) x, y, z = 10, 20, 30    # multiple assignment, uses tuples

(*@\ipyprompt@*) (y + z) / x
(*@\ipyreturn@*) 5

(*@\ipyprompt@*) x += 5                  # eqivalent to x = x + 5

(*@\ipyprompt@*) y *= 2                  # eqivalent to x = x * 2

(*@\ipyprompt@*) x, y, z
(*@\ipyreturn@*) (15, 40, 30)
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
\frametitle{Complex Numbers}
\reference{
More Examples: \url{http://docs.python.org/tutorial/introduction.html}
}
\begin{itemize}
\item Python natively supports complex numbers.
  \begin{itemize}
  \item Imaginary numbers are written with the \lstpy{j} or \lstpy{J} suffix.
  \end{itemize}
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) 1j * 1J
(*@\ipyreturn@*) (-1+0j)

(*@\ipyprompt@*) complex(3, 2)       # can also create with the 'complex' function
(*@\ipyreturn@*) (3+2j)

(*@\ipyprompt@*) a = (-1 + 3j) * 2j

(*@\ipyprompt@*) a
(*@\ipyreturn@*) (-6-2j)

(*@\ipyprompt@*) a.real              # access the real part
(*@\ipyreturn@*) -6.0

(*@\ipyprompt@*) a.imag              # access the imaginary part
(*@\ipyreturn@*) -2.0

(*@\ipyprompt@*) abs(a)              # abs(a) == sqrt(a.real**2 + a.imag**2)
(*@\ipyreturn@*) 6.324555320336759

(*@\ipyprompt@*) a.conjugate()       # the complex conjugate
(*@\ipyreturn@*) (-6+2j)
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
\frametitle{Boolean Operators}
\reference{
More info: \url{http://docs.python.org/library/stdtypes.html}
}
\begin{center}
\footnotesize
\begin{tabular}{|l|l|}
\hline
\rowcolor{blue!05!white}
Python & Result \\
\hline
\lstpy{x or y}  & if x is false, then y, else x (short-circuit) \\
\lstpy{x and y} & if x is false, then x, else y (short-circuit) \\
\lstpy{not x}   & if x is false, then \lstpy{True}, else \lstpy{False} \\
\hline
\multicolumn{2}{c}{} \\
\hline
\rowcolor{red!05!white}
MATLAB & Result \\
\hline
\lstmat{x || y} & if \lstmat{logical(x)}, then \lstmat{1}, else \lstmat{logical(y)} (short-circuit) \\
\lstmat{x && y} & if \lstmat{logical(x)}, then  \lstmat{logical(y)}, else \lstmat{0} (short-circuit) \\
\lstmat{\~x}    & if \lstmat{logical(x)}, then \lstmat{0}, else \lstmat{1} \\
\hline
\end{tabular}
\end{center}
\begin{itemize}
\item Examples
\end{itemize}
\vspace{-2em}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
> 0.0 || 'hello'
1
> 10 && (5 || 6)
1
> ~ 5
0
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
> 0.0 or 'hello'
'hello'
> 10 and (5 or 6)
5
> not 5
False
\end{pythonBlock}
\end{columns}
\end{frame}


\begin{frame}[fragile]
\frametitle{Comparisons}
\reference{
More info: \url{http://docs.python.org/library/stdtypes.html}
}
\begin{center}
\footnotesize
\begin{tabular}{|l|l|l|}
\hline
MATLAB & Python & Meaning \\
\hline
\lstmat{<}      & \lstpy{<}      & strictly less than \\
\lstmat{<=}     & \lstpy{<=}     & less than or equal \\
\lstmat{>}      & \lstpy{>}      & strictly greater than \\
\lstmat{>=}     & \lstpy{>=}     & greater than or equal \\
\lstmat{==}     & \lstpy{==}     & equal \\
\lstmat{\~=}    & \lstpy{!=}     & not equal \\
\emph{N/A}      & \lstpy{is}     & object identity \\
\emph{N/A}      & \lstpy{is not} & negated object identity \\
\hline
\end{tabular}
\end{center}
\begin{itemize}
\item These comparisons always return a Boolean value.
\item Comparison between different numeric types casts from
      \lstpy{int} to \lstpy{float} to \lstpy{complex} as needed.
      For example \lstpy{3.0 == 3} is \lstpy{True}.
\item Only ``not equal'' operators differ in syntax.
\item The concept of object identity is not found in MATLAB.
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Object Identity}
\reference{
More info: \url{http://docs.python.org/reference/datamodel.html}
}
\begin{itemize}
\item Every Python object has an identity.
      The function \lstpy{id(object)} returns a unique identifying integer.
\item The operation \lstpy{x is y} is equivalent to \lstpy{id(x) == id(y)}.
\item Assignment allows multiple variables to refer to the same object.
\item For immutable types (e.g.\ numeric types, strings, tuples)
      creation of new objects may or may not refer to same-valued exiting object.
\item For mutable type (e.g.\ list, dict) creation always creates a new object.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) x, y = 3, 4.4

(*@\ipyprompt@*) x == y, x is y, id(x), id(y)
(*@\ipyreturn@*) (False, False, 30294792, 32375168)

(*@\ipyprompt@*) x = 2 + 2.4

(*@\ipyprompt@*) x == y, x is y, id(x), id(y)      # here 'x is y' could be True or False
(*@\ipyreturn@*) (True, False, 37311776, 32375168)

(*@\ipyprompt@*) x = y

(*@\ipyprompt@*) x == y, x is y, id(x), id(y)      # here 'x is y' must be True
(*@\ipyreturn@*) (True, True, 32375168, 32375168)
\end{lstlisting}
\end{frame}


\subsection{Containers}

\begin{frame}[fragile]
\frametitle{Tuples}
\reference{
More info: \url{http://docs.python.org/library/stdtypes.html}
}
\begin{itemize}
  \item Tuples are immutable sequences of objects of any type.
  \item Tuple items are comma separated and often enclosed in parentheses.
  \item A trailing comma is required to make a tuple of length one.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) t = 1, 'hello', (3.14, None),  2.5

(*@\ipyprompt@*) t[0]        # access item by index
(*@\ipyreturn@*) 1

(*@\ipyprompt@*) t[0] = 2    # item assignment not allowed (immutable)
(*@\texttt{{\color{red}TypeError:} 'tuple' object does not support item assignment}@*)

(*@\ipyprompt@*) t[1:3]      # access a slice of the objects (start:end)
(*@\ipyreturn@*) ('hello', (3.14, None))

(*@\ipyprompt@*) len(t)      # the length of the tuple
(*@\ipyreturn@*) 4

(*@\ipyprompt@*) 2.5 in t    # test for inclusion
(*@\ipyreturn@*) True

(*@\ipyprompt@*) t + (5,)    # concatenate tuples
(*@\ipyreturn@*) (1, 'hello', (3.14, None), 2.5, 5)

(*@\ipyprompt@*) (1, 2) * 3  # concatenate n shallow copies
(*@\ipyreturn@*) (1, 2, 1, 2, 1, 2)
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
\frametitle{Strings}
\reference{
More info: \url{http://docs.python.org/library/string.html}
}
\begin{itemize}
  \item Strings are immutable sequences of characters.
  \item Strings are enclosed in single or double quotes.
  \item The concatenation and indexing syntax is the same as Tuple.
  \item Strings have many built-in functions.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) s = "Hello World"

(*@\ipyprompt@*) s.upper()                      # to upper case
(*@\ipyreturn@*) 'HELLO WORLD'

(*@\ipyprompt@*) s[3:5] + '- ' * 3 + s[::-1]    # concatenation and slicing
(*@\ipyreturn@*) 'lo- - - dlroW olleH'

(*@\ipyprompt@*) s.split()                      # string splitting
(*@\ipyreturn@*) ['Hello', 'World']

(*@\ipyprompt@*) ' - '.join(('a', 'b', 'c'))    # join strings with a seperator
(*@\ipyreturn@*) 'a - b - c'

(*@\ipyprompt@*) s.replace("Hello", "Goodbye")  # substring replacement
(*@\ipyreturn@*) 'Goodbye World'

(*@\ipyprompt@*) "item %05d has value %g" % (23, 3.14**2)  # operator % works like sprintf
(*@\ipyreturn@*) 'item 00023 has value 9.8596'
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
\frametitle{Lists}
\reference{
More info: \url{http://docs.python.org/library/stdtypes.html}
}
\begin{itemize}
  \item Lists are mutable sequences of objects of any type.
  \item List items are comma separated and enclosed in square brackets.
  \item The concatenation and indexing syntax is the same as Tuple.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) v = [1, 'hello', (3.14, None),  2.5]

(*@\ipyprompt@*) v[0] = 2         # item assignment

(*@\ipyprompt@*) v.append(0.5)    # append items to the end

(*@\ipyprompt@*) del v[2]         # delete an item

(*@\ipyprompt@*) v
(*@\ipyreturn@*) [2, 'hello', 2.5, 0.5]

(*@\ipyprompt@*) v.sort()         # sort items in place

(*@\ipyprompt@*) v
(*@\ipyreturn@*) [0.5, 2, 2.5, 'hello']

(*@\ipyprompt@*) v = ([],)*3      # a tuple with 3 shallow copies of the same empty list

(*@\ipyprompt@*) v[0].append(1)   # append to the first list in the tuple

(*@\ipyprompt@*) v                # all lists update because they are shallow copies
(*@\ipyreturn@*) ([1], [1], [1])
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
\frametitle{Dictionaries}
\reference{
More info: \url{http://docs.python.org/library/stdtypes.html}
}
\begin{itemize}
  \item Dictionaries are mutable mapping of one object to another.
  \item Key:value pairs are comma separated and enclosed in curly braces.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) d = {'a' : 1, 'b' : 2, 'c' : 3}

(*@\ipyprompt@*) d['a']       # access a value by key
(*@\ipyreturn@*) 1

(*@\ipyprompt@*) d['d'] = 4   # change a value or insert a new key:value

(*@\ipyprompt@*) d.keys()     # a list of dictionary keys
(*@\ipyreturn@*) ['a', 'c', 'b', 'd']

(*@\ipyprompt@*) d.values()   # a list of dictionary values
(*@\ipyreturn@*) [1, 3, 2, 4]

(*@\ipyprompt@*) d.items()    # a list of (key, value) tuples
(*@\ipyreturn@*) [('a', 1), ('c', 3), ('b', 2), ('d', 4)]
\end{lstlisting}
\end{frame}


\subsection{IPython Commands}


\begin{frame}
\frametitle{IPython Commands}
\reference{
\url{http://ipython.org/ipython-doc/rel-0.11/interactive/tutorial.html}
}
\begin{itemize}
\item IPython adds several interactive capabilities to standard Python.
  \begin{itemize}
  \item Tab Completion: start typing and hit the \texttt{Tab} key to get a list
        of possible completions.  Works for variables, functions, paths, etc.
  \pause
  \item History: access previous commands and their results
    \begin{itemize}
    \item adds \lstpy{__} and \lstpy{___} for second and third to last results.
    \item use the command \lstpy{history} to list the history of commands.
    \item use \lstpy{In[n]} to access the \lstpy{n}-th command string.
    \item use \lstpy{Out[n]} to access the \lstpy{n}-th result.
    \end{itemize}
  \pause
  \item Documentation: type \lstpy{objectName?} to get info about \lstpy{objectName}.
        Note, the standard Python \lstpy{help(objectName)} also provides some documentation.
  \pause
  \item Auto Call: lets you write functions as statements. \\
        For example, \lstpy{abs x} calls \lstpy{abs(x)}. MATLAB also allows this.
  \pause
  \item IPython provides many more features not covered here.
  \end{itemize}
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{IPython Commands}
\reference{
\url{http://ipython.org/ipython-doc/rel-0.11/interactive/tutorial.html}
}
\begin{itemize}
\item Examples of using IPython history
\end{itemize}
\setcounter{ipycommand}{0}
\begin{lstlisting}
(*@\ipyprompt@*) a = 1

(*@\ipyprompt@*) a += 1

(*@\ipyprompt@*) history
1: a = 1
2: a += 1
3: _ip.magic("history ")

(*@\ipyprompt@*) a
(*@\ipyreturn@*) 2

(*@\ipyprompt@*) In[2]
(*@\ipyreturn@*) u'a += 1\n'

(*@\ipyprompt@*) exec In[2]    # like 'eval' in MATLAB, Python also has 'eval' for expressions

(*@\ipyprompt@*) a
(*@\ipyreturn@*) 3

(*@\ipyprompt@*) Out[4] + Out[7]
(*@\ipyreturn@*) 5

\end{lstlisting}
\end{frame}
